package org.linphone.activity;

import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;


import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import com.leehuubsd.yiyanzb.R;
import com.umeng.analytics.MobclickAgent;

import com.android.volley.AuthFailureError;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnClickListener;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Toast;

public class New_Reg extends Activity {

	static ProgressDialog m_Dialog;
	String ProgressMsg = "";
	int a = 0;
	int b = 0;
	private String OEMID;
	private Button btn_sms;
	private RelativeLayout login_yy;
	public void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
	}

	public void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}
	@SuppressLint({ "WorldReadableFiles", "WorldWriteableFiles" })
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.newact_regedit);
		OEMID = getResources().getString(R.string.oem);
		btn_sms =(Button) findViewById(R.id.btn_sms);
		login_yy = (RelativeLayout) findViewById(R.id.login_yy);
		time1 = new TimeCount1(60000, 1000);// 构造CountDownTimer对象
//		GetMyPhoneNumber();
	}

	// 按钮 注册
	public void btn_Regedit(View v) {

		EditText InputPhone = (EditText) findViewById(R.id.editText1_ID);
		EditText InputVcode = (EditText) findViewById(R.id.editText2_PWD);
		EditText InputPWD = (EditText) findViewById(R.id.editText_pwd);
		EditText InputPWD2 = (EditText) findViewById(R.id.editText_pwd2);

		if (InputPhone.getText().toString().trim().equals("")) {
			Show_Dialog("", "请输入当前手机的手机号码");
		} else if (InputVcode.getText().toString().trim().equals("")) {
			Show_Dialog("", "请输入短信接收到的验证码");

		} else if (InputPWD.getText().toString().trim().equals("")) {
			Show_Dialog("", "请填写密码");
		} else if (InputPWD.getText().toString().trim()
				.equals(InputPWD2.getText().toString().trim()) == false) {
			Show_Dialog("", "两次密码不一致");
		}else{
			GetPostDate("/YXBp/dm9zb2Vt/UmVnaXN0ZXIz", 
					InputPhone.getText().toString().trim(), 
					InputPWD.getText().toString().trim(),
					InputVcode.getText().toString().trim());
		}

	}
	
	private void GetPostDate(final String Path,final String UserPhone, final String Upwd, final String vCode) {

		ProgressMsg = "正在注册，请稍后……";
		m_Dialog = ProgressDialog.show(New_Reg.this, "", ProgressMsg, true);
		m_Dialog.setIcon(android.R.drawable.ic_lock_idle_alarm);
		RequestQueue queue = Volley.newRequestQueue(this);
		StringRequest request = new StringRequest(Method.POST, getResources()
				.getString(R.string.http) + Path, new Listener<String>() {

			@Override
			public void onResponse(String arg0) {
				// TODO Auto-generated method stub
				Log.i("LOL", arg0);
				m_Dialog.dismiss();
				JSONObject object;
				try {
					object = new JSONObject(arg0);
					int i = object.getInt("retCode");
					if (i == 0) {
						Show_Toast("注册成功");
						finish();
						// 请求成功。等待短信即可！
					} else {
						// 请求失败，查看提示内容
						String s = object.getString("exception");
						Toast.makeText(getApplicationContext(),
								s + "(" + object.getInt("retCode") + ")",
								Toast.LENGTH_SHORT).show();
					}

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}, new com.android.volley.Response.ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError arg0) {
				// TODO Auto-generated method stub
				m_Dialog.dismiss();
				Show_Dialog("错误", "服务器忙，请稍后尝试登陆…");
			}
		}) {
			@Override
			protected Map<String, String> getParams() throws AuthFailureError {
				// TODO Auto-generated method stub
				String p = encryptBASE64(UserPhone);
				Map<String, String> map = new HashMap<String, String>();
				map.put("dXNlck5hbWUPQ", p);
				map.put("password", Upwd);
				map.put("parent", OEMID);
				map.put("os", "1");
				map.put("proxyId", OEMID);
				map.put("vCode", vCode);
				return map;
			}
		};
		queue.add(request);
	}
	
	/**
	 * BASE64 加密
	 * 
	 * @param str
	 * @return
	 */
	@SuppressLint("NewApi")
	public String encryptBASE64(String str) {
		if (str == null || str.length() == 0) {
			return null;
		}
		try {
			byte[] encode = str.getBytes("UTF-8");
			// base64 加密

			String s = new String(Base64.encode(encode, 0, encode.length,
					Base64.DEFAULT), "UTF-8");
			String s1 = s.replaceAll("=", "PQ");
			Log.i("LOL", s1);
			return s1;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		return null;
	}

	// 获取本机手机号码
	private void GetMyPhoneNumber() {
		TelephonyManager tm = (TelephonyManager) New_Reg.this
				.getSystemService(Context.TELEPHONY_SERVICE);
		String phoneId = tm.getLine1Number();
		if (phoneId != null && phoneId.startsWith("+86")) {
			phoneId = phoneId.substring(3);
		}
		EditText InputPhone = (EditText) findViewById(R.id.editText1_ID);
		InputPhone.setText(phoneId);
	}

	// 获得短信验证码
	public void btn_SMS(View v) {			
		btn_sms.setClickable(false);
		EditText InputPhone = (EditText) findViewById(R.id.editText1_ID);
		String Phones = InputPhone.getText().toString();
		if (!TextUtils.isEmpty(Phones)) {

			String path = getResources().getString(R.string.http)
					+ "/api/Account/GetValidateCodeNoUser?SrcPhone=[手机]&proxyId=[代理]&Type=[类型]"
							.replace("[手机]", Phones).replace("[代理]", OEMID)
							.replace("[类型]", "1");
			getdate(path.toString(),1);
		} else {
			Show_Toast("请填写手机号");
		}

	}
	public void back(View v){
		finish();
	}

	// 获得短信验证码
	public void btn_Audio(View v) {	
		btn_sms.setClickable(false);
		login_yy.setClickable(false);
		EditText InputPhone = (EditText) findViewById(R.id.editText1_ID);
		String Phones = InputPhone.getText().toString();
		if (!TextUtils.isEmpty(Phones)) {

			String path = getResources().getString(R.string.http)
					+ "/api/Account/GetValidateCodeNoUser?SrcPhone=[手机]&proxyId=[代理]&Type=[类型]"
							.replace("[手机]", Phones).replace("[代理]", OEMID)
							.replace("[类型]", "2");
			getdate(path.toString(),2);
		} else {
			Show_Toast("请填写手机号");
		}
	}

	// get12-22 16:02:38.657: I/LOL(4684): {"success":true}


	private void getdate(String path,final int i) {
		RequestQueue queue = Volley.newRequestQueue(this);
		String url = path;
		StringRequest request = new StringRequest(Method.GET, url,
				new Listener<String>() {
					@Override
					public void onResponse(String response) {
						Log.i("LOL", response);
						JSONTokener jsonTokener = new JSONTokener(response);
						try {
							JSONObject person = (JSONObject) jsonTokener
									.nextValue();
							if (person.getBoolean("success")) {
								Toast.makeText(getApplicationContext(), "获取验证码成功，请稍后！",
										Toast.LENGTH_SHORT).show();
								time1.start();// 开始计时
							} else {
								Toast.makeText(getApplicationContext(),
										person.getString("message"), Toast.LENGTH_SHORT).show();
								btn_sms.setClickable(true);
								login_yy.setClickable(true);
							}
						} catch (Exception e) {
							// TODO Auto-generated catch block
							Toast.makeText(getApplicationContext(), "服务器异常！",
									Toast.LENGTH_SHORT).show();
							btn_sms.setClickable(true);
							login_yy.setClickable(true);
							e.printStackTrace();
						}
					}
				}, new ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError arg0) {
						Log.i("log", "!!!!onErrorResponse" + arg0.toString());
						Toast.makeText(getApplicationContext(), "网络错误！",
								Toast.LENGTH_SHORT).show();
						btn_sms.setClickable(true);
						login_yy.setClickable(true);
					}
				});
		queue.add(request);
	}

	private TimeCount1 time1;

	/* 定义一个倒计时的内部类 */
	class TimeCount1 extends CountDownTimer {
		public TimeCount1(long millisInFuture, long countDownInterval) {
			super(millisInFuture, countDownInterval);// 参数依次为总时长,和计时的时间间隔
		}

		@Override
		public void onFinish() {// 计时完毕时触发
			btn_sms.setText("重新获取");
			btn_sms.setClickable(true);
			login_yy.setClickable(true);
		}

		@Override
		public void onTick(long millisUntilFinished) {// 计时过程显示
			btn_sms.setText(millisUntilFinished / 1000 + "秒");
		}
	}


	public void Show_Toast(String str) {
		Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
	}

	// 显示带有确定按钮的MSGBOX
	public void Show_Dialog(String tit, String txt) {
		Dialog dialog = new AlertDialog.Builder(this)
				.setIcon(R.drawable.ic_launcher).setTitle(tit).setMessage(txt)
				.setPositiveButton("确定", new OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
					}
				}).create();
		dialog.show();

	}

//	// 进去按钮
//	@SuppressLint({ "WorldWriteableFiles", "WorldReadableFiles" })
//	public void Show_Dialog_Loged(String tit, String txt, final String uphone,
//			final String UPWD) {
//		Dialog dialog = new AlertDialog.Builder(this)
//				.setIcon(R.drawable.ic_launcher).setTitle(tit).setMessage(txt)
//				.setPositiveButton("进入", new OnClickListener() {
//					public void onClick(DialogInterface dialog, int which) {
//
//						Intent intent = new Intent();
//						intent.putExtra("uPhone", uphone);
//						intent.putExtra("uPwd", UPWD);
//						intent.setClass(New_Reg.this, New_Login.class);
//						New_Reg.this.startActivity(intent);
//
//					}
//				}).create();
//		dialog.show();
//
//	}

	// HTTP GET
	public static String TryGetUrl(StringBuffer path) {
		HttpResponse httpResponse = null;
		try {
			HttpGet httpGet = new HttpGet(path.toString());
			httpResponse = new DefaultHttpClient().execute(httpGet);
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				String result = EntityUtils.toString(httpResponse.getEntity());
				String str = new String(result.getBytes("UTF-8"));
				return str;
			} else {
				return "x500";
			}
		} catch (Exception e) {
			return "x400";
		}
	}


}